/*Copyright 2010 by Matt Van Der Westhuizen */

package org.chaoticengine.ast.model;

import java.io.File;
import java.util.HashMap;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 *
 * @author Matt Van Der Westhuizen <mattpwest@gmail.com>
 */
@Root
public class TradeGoodFactory {
    protected static TradeGoodFactory instance = null;

    protected HashMap<String, TradeGood> goods = null;

    private TradeGoodFactory() {
        goods = new HashMap<String, TradeGood>();
    }

    public static TradeGoodFactory getInstance() {
        if (instance == null) {
            instance = TradeGoodFactory.load();
        }

        return(instance);
    }

    private static TradeGoodFactory load() {
        String filename = "data/TradeGoods.xml";
        Serializer srl = new Persister();
        File source = new File(filename);
        TradeGoodFactory tgf = null;
        try {
            tgf = srl.read(TradeGoodFactory.class, source);
        } catch (Exception ex) {
            tgf = new TradeGoodFactory();
            System.out.println("Warning: Failed to load TradeGoods for TradeGoodFactory from file '" + filename + "'.");
            ex.printStackTrace();
        }

        return(tgf);
    }

    @ElementMap(entry="Item", key="Name", value="TradeGood", inline=true, valueType=TradeGoodImplementation.class)
    public HashMap<String, TradeGood> getGoods() {
        return(goods);
    }

    @ElementMap(entry="Item", key="Name", value="TradeGood", inline=true, valueType=TradeGoodImplementation.class)
    public void setGoods(HashMap<String, TradeGood> goods) {
        this.goods = goods;
    }

    public TradeGood getTradeGood(String name) {
        return(goods.get(name.toLowerCase()));
    }
}
